//
//  GoodsDetailsController.m
//  BestPurchase
//
//  Created by ZSMAC on 2018/10/11.
//  Copyright © 2018年 张帅. All rights reserved.
//

#import "GoodsDetailsController.h"
#import "DetailsTopView.h"
#import "GoodsModel.h"
#import "GoodsDetailsCell.h"
#import "GoodsDetailsCellModel.h"
#import "DetailsNavBar.h"
#import "DetailsBottomBar.h"

@interface GoodsDetailsController () <UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property(nonatomic,strong)UITableView * tableView;
@property(nonatomic,strong)DetailsTopView * headerView;
@property(nonatomic,strong)GoodsModel *goodsModel;
@property(nonatomic,strong)NSMutableArray * cellDetailsArray;
@property(nonatomic,strong)DetailsNavBar * navBar;
@property(nonatomic,strong) MCustomButton * rollingTopBtn;
@property(nonatomic,strong)  DetailsBottomBar * bottomBar;
@end

@implementation GoodsDetailsController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed=YES;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated {
    if (!self.navigationController.navigationBarHidden) {
        self.navigationController.navigationBarHidden=YES;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self uiConfiguer];
    [self getData];
}
- (void)getData {
    BmobQuery   *bquery = [BmobQuery queryWithClassName:Goods_list_Name];
    @WeakObj(self);
    [bquery getObjectInBackgroundWithId:self.goodsId block:^(BmobObject *object,NSError *error){
        if (error){
            [ZSProgressHUD showDpromptText:@"获取详情失败"];
        } else {
           NSDictionary * dic = [object valueForKey:@"dataDic"];
           selfWeak.goodsModel = [GoodsModel mj_objectWithKeyValues:dic];
            [selfWeak dataSet];
        }
    }];
}
- (void)injected {
    //在这里面写的代码才能看效果  写完后 command + s 就出效果了
    self.view.backgroundColor=[UIColor yellowColor];
    for (UIView *view in self.view.subviews) {
        [view removeFromSuperview];
    }
    [self uiConfiguer];
}
- (void)dataSet {
    if (self.cellDetailsArray==nil) {
        self.cellDetailsArray=[[NSMutableArray alloc] init];
    }
     self.headerView.imageUrls = self.goodsModel.topRollingImages;
    [self.cellDetailsArray removeAllObjects];
   
    for (int i=0; i<2; i++) {
        GoodsDetailsCellModel *cellModel  = [[GoodsDetailsCellModel alloc] init];
        if (i==0) {
            cellModel.content=self.goodsModel.UnitPrice;
        } else {
            cellModel.content=self.goodsModel.title;
        }
        [self.cellDetailsArray addObject:cellModel];
    }
    
    for (NSString *content in self.goodsModel.details) {
        GoodsDetailsCellModel *cellModel  = [[GoodsDetailsCellModel alloc] init];
        if ([content containsString:@"https://"]) {
            cellModel.imageUrl=content;
        } else {
            cellModel.content=content;
        }
        [self.cellDetailsArray addObject:cellModel];
    }
    [self.tableView.mj_header endRefreshing];
    [self.tableView reloadData];
    
    NSArray * collectionIds = [MPublicManager sharedPublicManager].userModel.collections;
    if ([collectionIds containsObject:self.goodsId]) {
        [_bottomBar setCollection:YES];
    }
}
- (void)uiConfiguer {
     @WeakObj(self);
    CGFloat barHeight = 50;
    if (SCREEN_HEIGHT>=800) {
        barHeight+=34;
    }
    _bottomBar = [[DetailsBottomBar alloc]  initWithFrame:CGRectMake(0, SCREEN_HEIGHT-barHeight, SCREEN_WIDTH, barHeight)];
    [_bottomBar setClicked:^(NSString *title) {
        if ([title isEqualToString:@"收藏"]) {
            [selfWeak collection:!selfWeak.bottomBar.isCollection];
        }
    }];
    [self.view addSubview:_bottomBar];
    
    _headerView =  [[DetailsTopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/2)];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -StatusBar_Rect.size.height, SCREEN_WIDTH, SCREEN_HEIGHT-_bottomBar.height) style:UITableViewStyleGrouped];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.estimatedSectionFooterHeight=0;
    _tableView.estimatedSectionHeaderHeight=0;
    _tableView.scrollsToTop=NO;
    _tableView.tableHeaderView=_headerView;
    _tableView.backgroundColor=[UIColor whiteColor];
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
   
    _tableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [selfWeak getData];
    }];
    [self.view addSubview:_tableView];
    
    _navBar = [[DetailsNavBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, NavBarHeight)];
    [self.view addSubview:_navBar];
    
    
    _rollingTopBtn = [MCustomButton buttonWithType:UIButtonTypeCustom];
    _rollingTopBtn.frame=CGRectMake(SCREEN_WIDTH-65, SCREEN_HEIGHT-150, 50, 50);
    _rollingTopBtn.imageRect=CGRectMake(_rollingTopBtn.width/2-7.5, 5, 15, 15);
    _rollingTopBtn.titleRect=CGRectMake(_rollingTopBtn.width/2-20, 23, 40, 20);
    _rollingTopBtn.titleLabel.textAlignment=NSTextAlignmentCenter;
    [_rollingTopBtn setImage:[UIImage imageNamed:@"置顶"] forState:UIControlStateNormal];
    [_rollingTopBtn setTitle:@"顶部" forState:UIControlStateNormal];
    [_rollingTopBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _rollingTopBtn.titleLabel.font=Font(13);
    _rollingTopBtn.layer.cornerRadius=_rollingTopBtn.width/2;
    _rollingTopBtn.layer.masksToBounds=YES;
    _rollingTopBtn.layer.borderColor=[[[UIColor grayColor] colorWithAlphaComponent:0.6] CGColor];
    _rollingTopBtn.layer.borderWidth=0.5;
    _rollingTopBtn.backgroundColor=[[UIColor whiteColor] colorWithAlphaComponent:0.6];
    [_rollingTopBtn addTarget:self action:@selector(backTopClicked) forControlEvents:UIControlEventTouchUpInside];
    _rollingTopBtn.hidden=YES;
    [self.view addSubview:_rollingTopBtn];
    
}
- (void)backTopClicked {
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat bili =scrollView.contentOffset.y/(_headerView.height-20);
    _navBar.currentAlpha=bili;
    if (scrollView.contentOffset.y>100) {
        self.rollingTopBtn.hidden=NO;
    } else {
        self.rollingTopBtn.hidden=YES;
    }
     NSLog(@"scrollView.contentOffset.y %f %f",scrollView.contentOffset.y,bili);
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cellDetailsArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * identifier = @"GoodsDetailsCell";
    GoodsDetailsCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell=[[GoodsDetailsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
   
    GoodsDetailsCellModel *model =self.cellDetailsArray[indexPath.row];
    cell.indexPath=indexPath;
    [cell setGetCellHeight:^(CGFloat cellHeight) {
        model.cellHeight=cellHeight;
    }];
    cell.cellModel=model;
   
    return cell;
}
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodsDetailsCellModel *model = self.cellDetailsArray[indexPath.row];
    return model.cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

- (void)collection:(BOOL)add {
    BmobUser * user=[BmobUser currentUser];
    //此处是更新操作
    BmobObject  *gameScoreChange = [BmobObject objectWithoutDataWithClassName:@"_User" objectId:user.objectId];
    if (add) {
        [gameScoreChange addObjectsFromArray:@[self.goodsId] forKey:@"collections"];
    } else {
        [gameScoreChange removeObjectsInArray:@[self.goodsId] forKey:@"collections"];
    }
    @WeakObj(self);
    [gameScoreChange updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            [selfWeak.bottomBar setCollection:add];
            if (add) {
                [[MPublicManager sharedPublicManager].userModel.collections addObject:selfWeak.goodsId];
            } else {
                [[MPublicManager sharedPublicManager].userModel.collections removeObject:selfWeak.goodsId];
            }
        } else {
            [ZSProgressHUD showDpromptText:@"操作失败"];
            [selfWeak.bottomBar setCollection:!add];
        }
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
